#ifndef __WSGI_CHAT_HPP
#define __WSGI_CHAT_HPP
#include <errno.h>  // XXX 削除予定
#include "wsgi/middleware.hpp"
#include "concurrent/lock.hpp"
#include "concurrent/thread.hpp"
#include <vector>

namespace wsgi {

  /** 超絶適当ｗ */
  class Chat : public Middleware {
  private:
    std::string message;
    concurrent::Lock sync;

    std::vector<std::string> split(std::string str, const std::string& d) {
      std::vector<std::string> res;
      std::string::size_type pos = std::string::npos;
      while ((pos = str.find_first_of(d)) != std::string::npos) {
        res.push_back(str.substr(0, pos));
        str = str.substr(pos + 1);  // pos -> d の位置，+1 で次の標的
      }
      res.push_back(str);
      return res;
    }

  public:
    Chat()
      : Middleware(NULL)
    {}

    ~Chat() {
      printf("[Debug] Chat::dtor");
    }

    std::string call(Environment& env) {
      const std::string data = env.get("tcp.data", "");
      const std::vector<std::string> parts = split(data, ":");
      std::string cmd, msg;
      if (1 < parts.size()) {
        cmd = parts[0];
        msg = parts[1];
      }

      concurrent::synchronizer _(this->sync);
      if (data.empty() || cmd == "get") {
        printf("[Debug] wait... id=%u\n", (unsigned int)concurrent::Thread::current_id());
        this->sync.wait();
        printf("[Debug] wake up! id=%u\n", (unsigned int)concurrent::Thread::current_id());
        return this->message;
      } else {
        // post
        printf("[Debug] post! id=%u\n", (unsigned int)concurrent::Thread::current_id());
        this->message = msg;
        this->sync.broadcast();
        return "OK";
      }
    }
  };

}// namespace middle

#endif
